package cn.luo.dao;


import com.mongodb.client.gridfs.model.GridFSFile;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Repository
public class FileDao {


    // 获得SpringBoot提供的mongodb的GridFS对象
    @Autowired
    private GridFsTemplate gridFsTemplate;

    //把文件保存到存储桶
    public String  SaveMultipartFile(MultipartFile multiportFile) {
        try {
            String fileName = multiportFile.getOriginalFilename();
            // 输入流
            InputStream ins = multiportFile.getInputStream();
            // 获得文件类型
            String contentType = multiportFile.getContentType();
            // 将文件存储到mongodb中,mongodb 将会返回这个文件的具体信息
            ObjectId objectId = gridFsTemplate.store(ins, fileName, contentType);
            //将文件信息保存到关系型数据库中进行维护
            return objectId.toHexString();
        }catch (Exception e) {
            System.out.println("e = " + e);
        }
       return "添加失败";
    }


    //根据文件名检索对应的文件
    public InputStream getInpuStreamByFilename(String fileid) throws IOException {
        System.out.println("Getting file.. fileid=" + fileid);
        //查询桶
        GridFSFile result = gridFsTemplate
                .findOne(new Query(Criteria.where("_id").is(fileid)));
        if (result == null) {
            return null;
        }
        GridFsResource resource = gridFsTemplate.getResource(result);
        return resource.getInputStream();
    }
}
